// src/page/ProductPage.tsx
import React, { useContext, useEffect, useState, useCallback } from 'react'
import { Table, Button, Typography, Spin, Alert, Space, Modal, Popconfirm, message, Tag, Input } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons'
import { type Product } from '../api/service/ProductService'
import ProductContext from '../context/ProductContext'
import ProductDetailForm from '../component/ProductDetailForm'
import { fileService } from '../api/service/FileService'

const { Title } = Typography
const { Search } = Input

const ProductPage: React.FC = () => {
    const context = useContext(ProductContext)
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [editingProduct, setEditingProduct] = useState<Product | null>(null)
    const [coverUrls, setCoverUrls] = useState<Record<number, string>>({})
    const [detailUrls, setDetailUrls] = useState<Record<number, string>>({})
    const [loadingFileUrl, setLoadingFileUrl] = useState<Record<number, boolean>>({})
    const [searchKeyword, setSearchKeyword] = useState('')

    // 检查 context 是否存在
    if (!context) {
        throw new Error('ProductPage must be used within ProductProvider')
    }

    const {
        products,
        loading,
        error,
        fetchProducts,
        hasNext,
        fetchMoreProducts,
        deleteProduct,
        searchProducts
    } = context

    // 获取商品封面图片URL
    const fetchCoverUrl = useCallback(async (id: number, fileKey: string) => {
        // 设置加载状态
        setLoadingFileUrl(prev => ({ ...prev, [id]: true }));

        try {
            const downloadUrl = await fileService.getDownloadUrl(fileKey);
            setCoverUrls(prev => ({ ...prev, [id]: downloadUrl.url || '' }));
        } catch (error) {
            console.error('获取封面图片失败:', error);
            message.error('获取封面图片失败');
        } finally {
            setLoadingFileUrl(prev => {
                const newLoading = { ...prev };
                delete newLoading[id];
                return newLoading;
            });
        }
    }, []);

    // 获取商品详情图片URL
    const fetchDetailUrl = useCallback(async (id: number, fileKey: string) => {
        // 如果没有详情地址，则直接返回
        if (!fileKey) return;

        try {
            const downloadUrl = await fileService.getDownloadUrl(fileKey);
            setDetailUrls(prev => ({ ...prev, [id]: downloadUrl.url || '' }));
        } catch (error) {
            console.error('获取详情图片失败:', error);
            message.error('获取详情图片失败');
        }
    }, []);

    // 当产品列表变化时，获取所有封面图片URL
    useEffect(() => {
        products.forEach(product => {
            if (product.coverAddr && !coverUrls[product.id]) {
                fetchCoverUrl(product.id, product.coverAddr);
            }
        });
    }, [products, fetchCoverUrl, coverUrls]);

    // 组件挂载时获取商品数据
    useEffect(() => {
        fetchProducts(5)
    }, [fetchProducts])

    // 处理搜索
    const handleSearch = (value: string) => {
        setSearchKeyword(value)
        searchProducts(value, 5)
    }

    // 处理加载更多
    const handleLoadMore = () => {
        fetchMoreProducts(5)
    }

    // 处理创建商品
    const handleCreateProduct = () => {
        setEditingProduct(null)
        setIsModalVisible(true)
    }

    // 处理编辑商品
    const handleEditProduct = async (product: Product) => {
        setEditingProduct(product)
        setIsModalVisible(true)

        // 当点击编辑时，获取详情图片URL
        if (product.detailAddr && !detailUrls[product.id]) {
            await fetchDetailUrl(product.id, product.detailAddr);
        }

        // 如果还没有封面URL，也获取一下
        if (product.coverAddr && !coverUrls[product.id]) {
            await fetchCoverUrl(product.id, product.coverAddr);
        }
    }

    // 处理删除商品
    const handleDeleteProduct = async (id: number) => {
        try {
            const result = await deleteProduct(id)
            if (result) {
                // 删除商品后清理对应的封面URL缓存
                setCoverUrls(prev => {
                    const newUrls = { ...prev };
                    delete newUrls[id];
                    return newUrls;
                });
                setDetailUrls(prev => {
                    const newUrls = { ...prev };
                    delete newUrls[id];
                    return newUrls;
                });
                message.success('商品删除成功')
            } else {
                message.error('商品删除失败')
            }
        } catch (error) {
            console.error('删除商品时发生错误:', error)
            message.error('删除商品时发生错误')
        }
    }

    // 处理模态框取消
    const handleModalCancel = () => {
        setIsModalVisible(false)
        setEditingProduct(null)
    }

    // 处理操作成功
    const handleSuccess = () => {
        setIsModalVisible(false)
        setEditingProduct(null)
        // 操作成功后重新搜索或刷新列表
        if (searchKeyword) {
            searchProducts(searchKeyword, 5)
        }
    }

    const productColumns = [
        {
            title: '商品编号',
            dataIndex: 'id',
            key: 'id'
        },
        {
            title: '商品封面',
            dataIndex: 'coverAddr',
            key: 'coverAddr',
            render: (_: string, record: Product) => {
                const coverUrl = coverUrls[record.id];
                const isLoading = loadingFileUrl[record.id];

                return (
                    <div style={{ width: '100px', height: '100px', position: 'relative' }}>
                        {isLoading ? (
                            <Spin />
                        ) : coverUrl ? (
                            <img
                                src={coverUrl}
                                alt="商品封面"
                                style={{ width: '100px', height: '100px', objectFit: 'cover' }}
                            />
                        ) : (
                            <div style={{
                                width: '100px',
                                height: '100px',
                                backgroundColor: '#f0f0f0',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                color: '#999'
                            }}>
                                无封面
                            </div>
                        )}
                    </div>
                );
            }
        },
        {
            title: '商品名称',
            dataIndex: 'title',
            key: 'title',
            render: (text: string, record: Product) => (
                <Button
                    type="link"
                    onClick={() => handleEditProduct(record)}
                >
                    {text}
                </Button>
            )
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            render: (price: number) => `¥${price}`
        },
        {
            title: '库存',
            dataIndex: 'stockpile',
            key: 'stockpile'
        },
        {
            title: '冻结库存',
            dataIndex: 'stockpileFrozen',
            key: 'stockpileFrozen',
            render: (stockpileFrozen: number) => (
                <span style={{ color: stockpileFrozen > 0 ? 'darkred' : 'gray' }}>
                     {stockpileFrozen}
                </span>
            )
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (status: string) => (
                <Tag color={status === 'active' ? 'green' : 'red'}>
                    {status === 'active' ? '在售' : '下架'}
                </Tag>
            )
        },
        {
            title: '操作',
            key: 'action',
            render: (_: Product, record: Product) => (
                <Space size="middle">
                    <Button
                        type="link"
                        icon={<EditOutlined />}
                        onClick={() => handleEditProduct(record)}
                    >
                        编辑
                    </Button>
                    <Popconfirm
                        title="确认删除"
                        description="确定要删除这个商品吗？"
                        onConfirm={() => handleDeleteProduct(record.id)}
                        okText="确认"
                        cancelText="取消"
                    >
                        <Button
                            type="link"
                            danger
                            icon={<DeleteOutlined />}
                        >
                            删除
                        </Button>
                    </Popconfirm>
                </Space>
            ),
        },
    ]

    return (
        <div style={{
            height: 'calc(100vh - 112px)',
            overflowY: 'auto',
            scrollbarWidth: 'thin', // Firefox
            scrollbarColor: '#c1c1c1 #f1f1f1' // Firefox
        }}>
            <style>
                {`
                /* Webkit浏览器滚动条样式 */
                div::-webkit-scrollbar {
                    width: 4px;
                }
                
                div::-webkit-scrollbar-track {
                    background: #f1f1f1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb {
                    background: #c1c1c1;
                    border-radius: 10px;
                }
                
                div::-webkit-scrollbar-thumb:hover {
                    background: #a8a8a8;
                }
                `}
            </style>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 16 }}>
                <Title level={3}>商品管理</Title>
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleCreateProduct}
                >
                    添加商品
                </Button>
            </div>

            {/* 添加搜索栏 */}
            <div style={{ marginBottom: 16 }}>
                <Search
                    placeholder="请输入商品名称或描述"
                    allowClear
                    enterButton={<><SearchOutlined />搜索</>}
                    size="large"
                    onSearch={handleSearch}
                    style={{ width: 400 }}
                />
            </div>

            {error && (
                <Alert
                    message="数据加载失败"
                    description={error}
                    type="error"
                    showIcon
                    style={{ marginBottom: 16 }}
                />
            )}

            <Spin spinning={loading && products.length === 0}>
                <Table
                    dataSource={products.map(product => ({
                        ...product,
                        key: product.id
                    }))}
                    columns={productColumns}
                    pagination={false}
                />

                {hasNext && (
                    <div style={{ textAlign: 'center', padding: 20, marginTop: 20 }}>
                        <Button onClick={handleLoadMore} loading={loading}>
                            {loading ? '加载中...' : '加载更多'}
                        </Button>
                    </div>
                )}

                {!hasNext && products.length > 0 && (
                    <div style={{ textAlign: 'center', padding: 20, color: '#999' }}>
                        没有更多数据了
                    </div>
                )}
            </Spin>

            <Modal
                title={editingProduct ? "编辑商品" : "创建商品"}
                open={isModalVisible}
                onCancel={handleModalCancel}
                footer={null}
                width={800}
            >
                <ProductDetailForm
                    product={editingProduct}
                    coverUrl={editingProduct ? coverUrls[editingProduct.id] : undefined}
                    detailUrl={editingProduct ? detailUrls[editingProduct.id] : undefined}
                    onCancel={handleModalCancel}
                    onSuccess={handleSuccess}
                />
            </Modal>
        </div>
    )
}

export default ProductPage
